﻿using System;
using System.IO.Compression;
using System.Web;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public class CompressionModule : IHttpModule {
		#region IHttpModule

		/// <summary>
		/// 
		/// </summary>
		public void Dispose() {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		public void Init(HttpApplication context) {
			context.PostReleaseRequestState += new EventHandler(ContextPostReleaseRequestState);
		}

		#endregion

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ContextPostReleaseRequestState(object sender, EventArgs e) {
			var context = sender as HttpApplication;

			if (context.Response.StatusCode != 200) {
				return;
			}

			if (context.Request.Url.AbsolutePath.EndsWith("WebResource.axd", StringComparison.OrdinalIgnoreCase)) {
				return;
			}

			// Check accepted encodings.
			string acceptedEncodings = context.Request.Headers.Get("Accept-Encoding");
			if (string.IsNullOrEmpty(acceptedEncodings))
				return;

			acceptedEncodings = acceptedEncodings.ToLower();

			// Check content type.
			string contentType = context.Response.ContentType;
			if (string.IsNullOrEmpty(contentType))
				return;

			contentType = contentType.ToLower();

			// Check accepted encodings and content type.
			if (acceptedEncodings.Contains("gzip")
				&& (contentType == "text/html" || contentType == "text/css")) {
				try {
					context.Response.AppendHeader("Content-Encoding", "gzip");
					context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
				} catch {
					//
				}
			}
		} // end of ContextPostReleaseRequestState.
	} // end of CompressionModule.
}
